package ${pPackage}.shiro.session;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class CustomSessionManager extends DefaultWebSessionManager {
  /**
   * 头信息中具有sessionid
   * 请求头：Authorization： sessionid
   * <p>
   * 指定sessionId的获取方式
   */
  protected Serializable getSessionId(ServletRequest request, ServletResponse response) {

    /**
     * 敏感头信息Authorization,Cookie,Set-Cookie默认网关服务是不转发的，也就下游服务获取不到
     * 在配置文件里设置zuul.sensitive-headers设置为空，就可以获取到了
     * 或者换成别的单词:如 token...
     */
    //获取请求头Authorization中的数据
    String id = WebUtils.toHttp(request).getHeader("Authorization");

    if (StringUtils.isEmpty(id)) {
      //如果没有携带，生成新的sessionId
      return super.getSessionId(request, response);
    } else {
      //请求头信息：bearer sessionid
      id = id.replaceAll("Bearer ", "");
      //返回sessionId；
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
      return id;
    }
  }
}
